package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook address = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (address==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart=new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list==null || list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(address.getProvinceName()+address.getDistrictName()+address.getDetail());
        Long orderId = orderMapper.selectOrderId();
        orderMapper.insert(orders);
        //向订单明细表插入n条数据
        for (ShoppingCart cart:list){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetailMapper.addOne(orderDetail);
        }
        shoppingCartMapper.deleteByUserId(userId);
        //返回vo
        OrderSubmitVO submitVO=OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return submitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        JSONObject jsonObject=new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //调用存储过程
        int orderCount = orderMapper.getOrderCount();
        log.info("截至目前，共有订单："+orderCount+"条");
        //向浏览器发送数据type，orderId，content
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        // 分页条件查询
        Page<EQ> page = orderMapper.pageQuery(ordersPageQueryDTO,ordersPageQueryDTO.getQpositionList());
        List<OrderVO> list = new ArrayList<>();
        // 查询出订单明细，并封装入OrderVO进行响应
//        if (page != null && page.getTotal() > 0) {
//            for (Orders orders : page) {
//                Long orderId = orders.getId();// 订单id
//                // 查询订单明细
//                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
//
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//
//                list.add(orderVO);
//            }
//        }
        return new PageResult(page.getTotal(), list);
    }
    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }
    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将订单详情对象转换为购物清单对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的电力信息重新复制到购物清单对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        for (ShoppingCart one:shoppingCartList){
            shoppingCartMapper.insertBatch(one);
        }
    }
    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
//        for(String qposition:qpositionList){
//            orderMapper.pageQuery(ordersPageQueryDTO,qposition);
//        }

        System.out.println(ordersPageQueryDTO.getQpositionList());
        Page<EQ> page = orderMapper.pageQuery(ordersPageQueryDTO,ordersPageQueryDTO.getQpositionList());
        List<EQ> orderVOList = getOrderVOList(page);
        System.out.println("OOOOOO+OOOO:"+orderVOList);
        return new PageResult(page.getTotal(), orderVOList);
    }
    private List<EQ> getOrderVOList(Page<EQ> page) {
        List<EQ> orderVOList = new ArrayList<>();
        List<EQ> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (EQ orders : ordersList) {
                //OrderVO orderVO = new OrderVO();
                EQ eq=new EQ();
                BeanUtils.copyProperties(orders, eq);
//                String orderDishes = getOrderDishesStr(orders);
//                orderVO.setOrderDishes(orderDishes);
//                orderVOList.add(orderVO);
            }
        }
        return ordersList;
    }
    private String getOrderDishesStr(Orders orders) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        return String.join("", orderDishList);
    }
    public OrderStatisticsVO statistics() {

         Integer newEnergy=orderMapper.countStatus(2);
        // '环保工程',
         Integer huanbao=orderMapper.countStatus(3);
        //'建筑工程施工总承包',
         Integer jianzhu=orderMapper.countStatus(4);
        // '钢结构工程',
         Integer gangjiegou=orderMapper.countStatus(5);
        // '园林设计、绿化养护',
         Integer yuanlin=orderMapper.countStatus(6);
        // '水利水电工程',
         Integer shuili=orderMapper.countStatus(7);
        // '市政工程',
         Integer shizheng=orderMapper.countStatus(8);
        //'电力工程',
         Integer dianli=orderMapper.countStatus(9);
        // '机电工程',
         Integer jidian=orderMapper.countStatus(10);
        // '消防设施工程',
         Integer xiaofang=orderMapper.countStatus(11);
        // '铁路工程',
         Integer tielu=orderMapper.countStatus(12);
        // '公路工程',
         Integer gonglu=orderMapper.countStatus(13);
        // '桥梁工程',
         Integer qiaolianggongcheng=orderMapper.countStatus(14);
        // '隧道工程',
         Integer suidao=orderMapper.countStatus(15);
        // '矿山',
         Integer kuangshan=orderMapper.countStatus(16);
        // '桥梁',
         Integer qiaoliang=orderMapper.countStatus(17);
        //'特种工程、设备生产',
         Integer tezhong=orderMapper.countStatus(18);
        // '机场、航道、港口',
         Integer jichang=orderMapper.countStatus(19);
        // '石油化工',
         Integer shiyou=orderMapper.countStatus(20);
        //'装饰装修',
         Integer zhuangshi=orderMapper.countStatus(21);
        //'防水防腐',
         Integer fangshui=orderMapper.countStatus(22);
        //'运行维护工程',
         Integer yunxing=orderMapper.countStatus(23);
        // '冶金',
         Integer yejin=orderMapper.countStatus(24);
        //'施工劳务',
         Integer shigong=orderMapper.countStatus(25);
        //'生态地质矿山勘察',
         Integer shengtai=orderMapper.countStatus(26);
        //'拆除爆破',
         Integer chaichu=orderMapper.countStatus(27);
        // '电子与智能化',
         Integer dianzi=orderMapper.countStatus(28);
        //'河湖治理',
         Integer hehu=orderMapper.countStatus(29);
        // '混凝土',
         Integer hunningtu=orderMapper.countStatus(30);
        //'起重设备',
         Integer qizhong=orderMapper.countStatus(31);
        // '通信工程',
         Integer tongxin=orderMapper.countStatus(32);
        //'设计',
         Integer sheji=orderMapper.countStatus(33);
        // '电缆电路',
         Integer dianlu=orderMapper.countStatus(34);
        // '城市及道路照明',
         Integer chengshi=orderMapper.countStatus(35);
        // '保安',
         Integer baoan=orderMapper.countStatus(36);
        // '环卫',
         Integer huanwei=orderMapper.countStatus(37);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setHuanbao(huanbao);
        orderStatisticsVO.setDianli(dianli);
        orderStatisticsVO.setChaichu(chaichu);
        orderStatisticsVO.setBaoan(baoan);
        orderStatisticsVO.setChengshi(chengshi);
        orderStatisticsVO.setDianlu(dianlu);
        orderStatisticsVO.setXiaofang(xiaofang);
        orderStatisticsVO.setHehu(hehu);
        orderStatisticsVO.setFangshui(fangshui);
        orderStatisticsVO.setKuangshan(kuangshan);
        orderStatisticsVO.setGonglu(gonglu);
        orderStatisticsVO.setDianzi(dianzi);
        orderStatisticsVO.setJichang(jichang);
        orderStatisticsVO.setYunxing(yunxing);
        orderStatisticsVO.setQiaoliang(qiaoliang);
        orderStatisticsVO.setQiaolianggongcheng(qiaolianggongcheng);
        orderStatisticsVO.setZhuangshi(zhuangshi);
        orderStatisticsVO.setYuanlin(yuanlin);
        orderStatisticsVO.setYejin(yejin);
        orderStatisticsVO.setTongxin(tongxin);
        orderStatisticsVO.setTielu(tielu);
        orderStatisticsVO.setSuidao(suidao);
        orderStatisticsVO.setTezhong(tezhong);
        orderStatisticsVO.setShuili(shuili);
        orderStatisticsVO.setShizheng(shizheng);
        orderStatisticsVO.setShiyou(shiyou);
        orderStatisticsVO.setShigong(shigong);
        orderStatisticsVO.setShengtai(shengtai);
        orderStatisticsVO.setSheji(sheji);
        orderStatisticsVO.setQizhong(qizhong);
        orderStatisticsVO.setNewEnergy(newEnergy);
        orderStatisticsVO.setJidian(jidian);
        orderStatisticsVO.setJianzhu(jianzhu);
        orderStatisticsVO.setHunningtu(hunningtu);
        orderStatisticsVO.setHuanwei(huanwei);
        orderStatisticsVO.setGangjiegou(gangjiegou);
        return orderStatisticsVO;
    }
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }
    @Override
    public void reminder(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB == null ) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
